package com.itheima.common.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author：shenkunlin
 * @date： 2021/8/22 12:05
 * @Description：
 ***/
public class RequestContext {

    /***
     * 获取response
     */
    public static HttpServletResponse getResponse(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes.getResponse();
    }


    /***
     * 获取request
     */
    public static HttpServletRequest getRequest(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes==null || attributes.getRequest()==null){
            return null;
        }
        return attributes.getRequest();
    }

    /***
     * RequestContextHolder:获取当前请求中的封装对象信息
     *   请求信息HttpServletRequest
     *   响应信息HttpServletResponse
     *   会话信息HttpSession
     */
    public static String getNode(String key){
        /***
         * 1:获取HttpServletRequest
         * 2:获取指定请求头信息
         * 3:将指定请求头信息转换成需要的对象
         */
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        return request.getHeader(key);
    }

    /**
     * 获取指定的Token
     * @return
     */
    public static String getToken(String key){
        return getNode(key==null? "token":key);
    }

    /***
     * 把Token转成Map
     */
    public static Map<String,Object> tokenMap(String key){
        //获取令牌
        String token = getToken(key==null? null:key);
        //转成Map
        return JwtUtil.parse(token);
    }

    /***
     * 获取Token中指定key的数据
     */
    public static <T> T getNodeValue(String key){
        return (T) tokenMap(null).get(key);
    }
}
